package com.suixun.queue;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentLinkedQueue;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.google.gson.Gson;
import com.suixun.Constants;
import com.suixun.dao.RptAlarmMapper;
import com.suixun.dao.TeacherAlarmMapper;
import com.suixun.entity.RptAlarm;
import com.suixun.entity.StdObjectinfo;
import com.suixun.entity.StdPeopleinfo;
import com.suixun.entity.TeacherAlarm;
import com.suixun.service.ParentService;
import com.suixun.service.StudentService;
import com.suixun.service.credits.SendGoodsService;
import com.suixun.util.Constant;
import com.suixun.vo.SendGoodsVO;

import cn.jiguang.common.ClientConfig;
import cn.jpush.api.JPushClient;
import rop.utils.spring.CollectionUtils;

/**
 * <p>
 * Title: SendGoodsDeal
 * </p>
 * <p>
 * 功能描述: 推送发券
 * </p>
 * 
 * @author 陈显强
 * @date 2017年12月19日下午9:08:38
 * @version 1.0
 */
public class SendGoodsDeal extends BaseDeal {

	private static ConcurrentLinkedQueue<SendGoodsVO> queue = new ConcurrentLinkedQueue<SendGoodsVO>();

	private final JPushClient guardianClient = new JPushClient(Constant.JpushConstant.MASTER_SECRET,
			Constant.JpushConstant.APP_KEY, null, ClientConfig.getInstance());

	private final JPushClient teacherClient = new JPushClient(Constant.JpushConstant.TEACHER_MASTER_SECRET,
			Constant.JpushConstant.TEACHER_APP_KEY, null, ClientConfig.getInstance());

	private final static int count = 500;

	protected final static Log logger = LogFactory.getLog(SendGoodsDeal.class);

	@Resource
	private SendGoodsService sendGoodsService;
	@Resource
	private StudentService studentService;
	@Resource
	private ParentService parentService;
	@Resource
	private TeacherAlarmMapper teacherAlarmMapper;
	@Resource
	private RptAlarmMapper rptAlarmMapper;

	public static void add(SendGoodsVO sendGoodsVo) {
		queue.offer(sendGoodsVo);
	}

	public void execute() throws InterruptedException {
		while (true) {
			try {
				if (!queue.isEmpty()) {
					SendGoodsVO sendGoods = queue.poll();
					if (sendGoods != null) {
						pushCoupon(sendGoods.getPeopletels(), sendGoods.getContent(), sendGoods.getGoodsNumberList(),
								sendGoods.getRange());
					} else {
						Thread.sleep(1000);
					}
				} else {
					Thread.sleep(1000);
				}
			} catch (Exception e) {
				logger.error(e);
				Thread.sleep(5000);
				continue;
			}
		}
	}

	private void pushCoupon(Set<String> peopletels, String content, List<String> goodsNumberList, Integer range)
			throws InterruptedException {
		if (CollectionUtils.isEmpty(peopletels) || CollectionUtils.isEmpty(goodsNumberList)) {
			return;
		}
		Thread.sleep(20000);
		List<String> telephoneList = new ArrayList<>();
		telephoneList.addAll(peopletels);
		List<String> peopletelList = new ArrayList<>();
		String model = "gift";
		if (goodsNumberList.size() == 1) {
			model = "card";
		}
		String time = Long.valueOf(new Date().getTime()).toString();

		// 保存消息
		addMessage(peopletels, content, goodsNumberList, range, model, time);

		for (int i = 0; i < telephoneList.size(); i = i + count) {
			if (i + count >= telephoneList.size()) {
				peopletelList = telephoneList.subList(i, telephoneList.size());
			} else {
				peopletelList = telephoneList.subList(i, i + count);
			}
			if (goodsNumberList.size() == 1) {
				send(model, peopletelList, content, goodsNumberList.get(0), range, time);
			} else {
				send(model, peopletelList, content, StringUtils.join(goodsNumberList, ","), range, time);
			}
			Thread.sleep(10000);
		}

	}

	private void send(String model, List<String> peopletelList, String content, String goodsNumbers, Integer range,
			String time) {
		String title = "大礼包";
		if ("card".equals(model)) {
			title = "优惠券";
		}
		if ("1".equals(String.valueOf(range))) {
			if ("DEV".equals(Constants.get_platform_env())) {
				JiGuangSendPush(peopletelList, title, content, false, false, null, teacherClient, goodsNumbers, model,
						time); // 推测试环境
			} else {
				JiGuangSendPush(peopletelList, title, content, true, false, null, teacherClient, goodsNumbers, model,
						time); // 推生产环境
			}
		} else if ("2".equals(String.valueOf(range))) {
			if ("DEV".equals(Constants.get_platform_env())) {
				JiGuangSendPush(peopletelList, title, content, false, false, null, guardianClient, goodsNumbers, model,
						time); // 推测试环境
			} else {
				JiGuangSendPush(peopletelList, title, content, true, false, null, guardianClient, goodsNumbers, model,
						time); // 推生产环境
			}
		}
	}

	private void addMessage(Set<String> peopletels, String content, List<String> goodsNumberList, Integer range,
			String model, String time) {
		if (CollectionUtils.isEmpty(peopletels)) {
			return;
		}
		if ("1".equals(String.valueOf(range))) {
			// 保存教师消息
			for (String peopletel : peopletels) {
				addTeacherMessage(peopletel, content, StringUtils.join(goodsNumberList, ","), model, time);
			}
		} else if ("2".equals(String.valueOf(range))) {
			// 保存家长消息,获取家长下的所有objectid,这里的家长必须是孩子的主监护人，普通监护人不保存消息
			List<StdObjectinfo> objectinfoList = null;
			for (String peopletel : peopletels) {
				objectinfoList = studentService.getStudentsByMainGuardian(peopletel);
				if (!CollectionUtils.isEmpty(objectinfoList)) {
					for (StdObjectinfo stdObjectinfo : objectinfoList) {
						addGuardianMessage(stdObjectinfo.getObjectid(), content, StringUtils.join(goodsNumberList, ","),
								model, time);
					}
				}
			}
		}
	}

	/**
	 * <p>
	 * Title: addGuardianMessage
	 * </p>
	 * <p>
	 * 功能描述: 保存家长端消息
	 * </p>
	 * 
	 * @param objectid
	 * @param content
	 * @param goodsNumbers
	 * @param model
	 */
	private void addGuardianMessage(Integer objectid, String content, String goodsNumbers, String model, String time) {
		RptAlarm rptAlarm = new RptAlarm();
		Map<String, Object> map = new HashMap<>();
		map.put("content", content);
		map.put("goodsNumbers", goodsNumbers);
		map.put("isReceive", false);
		map.put("model", model);
		map.put("time", time);
		rptAlarm.setAlarmtype(50);
		rptAlarm.setObjectid(objectid);
		rptAlarm.setStatus(0);
		rptAlarm.setOthervalue(new Gson().toJson(map));
		rptAlarm.setRecvtime(new Date());
		rptAlarmMapper.insertSelective(rptAlarm);
	}

	/**
	 * <p>
	 * Title: addTeacherMessage
	 * </p>
	 * <p>
	 * 功能描述: 保存教师端消息
	 * </p>
	 * 
	 * @param peopletel
	 * @param content
	 * @param goodsNumbers
	 * @param model
	 */
	private void addTeacherMessage(String peopletel, String content, String goodsNumbers, String model, String time) {
		StdPeopleinfo peopleinfo = parentService.getPeopleinfo(peopletel);
		if (peopleinfo == null) {
			return;
		} else {
			TeacherAlarm teacherAlarm = new TeacherAlarm();
			teacherAlarm.setIsread(0);
			teacherAlarm.setReceiveTime(new Date());
			teacherAlarm.setType(7);
			teacherAlarm.setPeopleid(peopleinfo.getPeopleid());
			Map<String, Object> map = new HashMap<>();
			map.put("content", content);
			map.put("goodsNumbers", goodsNumbers);
			map.put("isReceive", false);
			map.put("model", model);
			map.put("time", time);
			teacherAlarm.setContent(new Gson().toJson(map));
			teacherAlarmMapper.insertSelective(teacherAlarm);
		}
	}
}
